'use strict';

const Controller = require('egg').Controller;
const OSS = require('ali-oss');
const jwt = require('jsonwebtoken');

const OSSPage = new OSS({
  bucket: '1907abucket',
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tM8EcmsJrB5FAvb2Kne',
  accessKeySecret: 'e1KnuO0cVrmV5MqReD85SZvTjP3eGD',
});

class UpLoadController extends Controller {
  async upload() {
    const { ctx, app } = this;

    // 获取前端请求头中的token
    const { authorization } = ctx.request.headers;

    // 获取前端传来的文件流信息
    const file = ctx.request.files[0];

    // 通过时间戳生成文件名称
    const filename = new Date().getTime() + file.filename;

    // 将文件上传至 阿里云  file.filepath:上传文件时 文件所在的临时路径
    const data = await OSSPage.put(filename, file.filepath);

    // 解析token  id:当前登录人的id
    const id = jwt.verify(authorization, '1907A');

    // 通过id 更新数据库中用户的头像
    await app.mysql.update('userlist', { id, img: data.url });

    ctx.body = {
      data,
    };
  }

  async editUplaod() {
    const { ctx } = this;

    const file = ctx.request.files[0];

    const filename = new Date().getTime() + file.filename;

    const data = await OSSPage.put(filename, file.filepath);

    ctx.body = {
      code: 1,
      msg: '上传成功',
      data,
    };
  }
}

module.exports = UpLoadController;
